<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="showDialog = true"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table border="" :data="list">
              <el-table-column label="序号" type="index" width="120" />
              <el-table-column label="角色名称" prop="name" width="240" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template #default="{row}">
                  <el-button size="small" type="success" @click="assignPerm(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="editRole(row.id)">编辑</el-button>
                  <el-button size="small" type="danger" @click="delRole(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination layout="prev,pager,next" :total="page.total" :page-size="page.pagesize" @current-change="currentChange" />
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="公司信息">
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="formData.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="formData.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="formData.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="formData.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>

      <el-dialog :title="titleText" :visible="showDialog" @close="btnCancel">
        <el-form v-if="showDialog" ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="btnCancel">取消</el-button>
            <el-button size="small" type="primary" @click="btnOK">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>

      <!-- 编辑权限弹窗 -->
      <el-dialog title="分配权限" :visible="showPermDialog" @close="btnPermCancel">
        <!-- 权限是一颗树 -->
        <!-- 将数据绑定到组件上 -->
        <!-- check-strictly 如果为true 那表示父子勾选时  不互相关联 如果为false就互相关联 -->
        <!-- id作为唯一标识 -->
        <!-- <el-tree
          :show-checkbox="true"
          :check-strictly="true"
          :default-checked-keys="selectCheck"
          node-key="id"
        /> -->
        <el-tree
          ref="permTree"
          :data="permData"
          :props="{label: 'name'}"
          :default-expand-all="true"
          :show-checkbox="true"
          :check-strictly="true"
          node-key="id"
        />
        <!-- 确定 取消 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button type="primary" size="small" @click="btnPermOK">确定</el-button>
            <el-button size="small" @click="btnPermCancel">取消</el-button>
          </el-col>
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getCompanyInfo, getRoleList, delRole, getRoleDetail, updateRole, addRole, assignPermission } from '@/api/setting'
import { getPermissionList } from '@/api/permission'
import { listToTreeData } from '@/utils'
export default {
  data() {
    return {
      showPermDialog: false,
      permData: [],
      userId: '',
      formData: {
        // 公司名称
        name: '',
        // 公司地址
        companyAddress: '',
        // 公司邮箱
        mailbox: '',
        // 备注
        remarks: ''
      },
      // 翻页设定对象
      page: {
        // 当前页码
        page: 1,
        // 每页显示的条数
        pagesize: 2,
        // 总数
        total: 0
      },
      // 角色列表数组
      list: [],
      showDialog: false,
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '该项不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '该项不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    titleText() {
      return this.roleForm.id ? '编辑角色' : '新增角色'
    }
  },
  created() {
    // 封装函数,获取企业信息
    this.getCompanyInfo()
    // 获取角色列表
    this.getRoleList()
  },
  methods: {
    async assignPerm(id) {
      this.userId = id
      // 获取全部权限列表
      this.permData = listToTreeData(await getPermissionList(), '0')
      // 获取当前被点击的角色的权限列表
      const { permIds } = await getRoleDetail(id)
      // 弹出弹窗
      this.showPermDialog = true

      this.$nextTick(() => {
        this.$refs.permTree.setCheckedKeys(permIds)
      })
    },

    async btnPermOK() {
      // 发请求
      //  拿到数据
      const permIds = this.$refs.permTree.getCheckedKeys()
      const id = this.userId
      // 发送api请求
      await assignPermission({
        id,
        permIds
      })
      // 提醒用户
      this.$message.success('修改成功')
      // 关闭弹窗
      this.showPermDialog = false
    },
    btnPermCancel() {
      //  清空数据
      this.$refs.permTree.setCheckedKeys([])
      //  关闭弹窗
      this.showPermDialog = false
    },

    async getCompanyInfo() {
      // 根据id获取企业信息
      this.formData = await getCompanyInfo(this.$store.state.user.userInfo.companyId)
    },
    async getRoleList() {
      const { rows, total } = await getRoleList(this.page)
      this.list = rows
      this.page.total = total
    },
    // newPage是当前点击的页码
    currentChange(newPage) {
      // 将当前页码赋值给当前的最新页码
      this.page.page = newPage
      this.getRoleList()
    },
    // 删除角色
    async delRole(id) {
      try {
        // 二次校验
        await this.$confirm('确定要删除该角色吗?')
        // 发请求
        await delRole(id)
        if (this.list.length === 1 && this.page.page > 1) {
          this.page.page--
        }
        // 提示用户
        this.$message.success('删除成功')
        // 加载数据
        this.getRoleList()
      } catch (error) {
        console.log(error)
      }
    },

    async editRole(id) {
      // 回显数据
      this.roleForm = await getRoleDetail(id)
      // 显示弹窗
      this.showDialog = true
    },

    // 点击确认按钮的业务处理
    async btnOK() {
      // 验证
      await this.$refs.roleForm.validate()
      // 发送请求
      // 有id发送编辑请求
      if (this.roleForm.id) {
        await updateRole(this.roleForm)
      } else {
        // 没有id发送新增请求
        await addRole(this.roleForm)
      }
      // 提示用户
      this.$message.success('操作成功')
      // 关闭弹窗
      this.showDialog = false
      // 重新加载数据
      this.getRoleList()
    },

    // 点击取消的业务处理
    btnCancel() {
      // 清理表单
      this.roleForm = {
        name: '',
        description: ''
      }
      // 清理验证
      this.$refs.roleForm.resetFields()
      // 关闭弹窗
      this.showDialog = false
    }
  }
}
</script>

<style>

</style>
